<template>
  <div class="settings-container" v-loading="loading" element-loading-text="加载中...">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h2>通知设置</h2>
        </div>
      </template>
      
      <div class="tab-content">
        <h3>邮件通知设置</h3>
        <el-form :model="combinedSettings" :rules="formRules" label-width="180px" class="settings-form" ref="formRef">
          <el-form-item label="是否启用邮件通知">
            <el-switch v-model="combinedSettings.enableEmail" @change="autoSaveEmailSettings" />
          </el-form-item>
          
          <el-form-item label="邮件服务器 (SMTP)" prop="smtpServer">
            <el-input v-model="combinedSettings.smtpServer" placeholder="smtp.example.com">
              <template #append>
                <el-select v-model="selectedSmtpProvider" placeholder="常用服务器" style="width: 120px" @change="selectSmtpProvider">
                  <el-option label="163邮箱" value="163" />
                  <el-option label="QQ邮箱" value="qq" />
                  <el-option label="Gmail" value="gmail" />
                  <el-option label="企业邮箱" value="enterprise" />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="端口" prop="smtpPort">
            <el-input-number v-model="combinedSettings.smtpPort" :min="1" :max="65535" :step="1" controls-position="right" />
          </el-form-item>
          
          <el-form-item label="发件人邮箱" prop="senderEmail">
            <el-input v-model="combinedSettings.senderEmail" placeholder="sender@example.com" />
          </el-form-item>
          
          <el-form-item label="邮箱密码/授权码" prop="emailPassword">
            <el-input v-model="combinedSettings.emailPassword" type="password" placeholder="邮箱密码或授权码" show-password />
          </el-form-item>
          
                    <el-form-item label="是否使用SSL">
            <el-switch v-model="combinedSettings.useSSL" @change="autoSaveEmailSettings" />
          </el-form-item>
          
          <el-form-item label="测试邮件连接">
            <el-button 
              type="primary" 
              :loading="testingConnection" 
              @click="testConnection"
              :disabled="!combinedSettings.enableEmail || !combinedSettings.smtpServer || !combinedSettings.senderEmail || !combinedSettings.emailPassword"
            >
              {{ testingConnection ? '测试中...' : '测试连接' }}
            </el-button>
            <div class="form-tip">
              <el-text type="info" size="small">测试邮件连接是否正常</el-text>
            </div>
          </el-form-item>
          
          <el-divider content-position="left">通知触发条件</el-divider>
          
          <el-form-item label="新订单创建时通知">
            <el-switch v-model="combinedSettings.notifyOnCreate" @change="autoSaveNotificationSettings" />
          </el-form-item>
          
          <el-form-item label="订单状态变更时通知">
            <el-switch v-model="combinedSettings.notifyOnStatusChange" @change="autoSaveNotificationSettings" />
          </el-form-item>
          
          <el-form-item label="订单签收时通知">
            <el-switch v-model="combinedSettings.notifyOnDelivered" @change="autoSaveNotificationSettings" />
          </el-form-item>
          
          <el-divider content-position="left">邮件模板</el-divider>
          
          <el-form-item label="新订单通知模板">
            <el-input v-model="combinedSettings.createTemplate" type="textarea" :rows="3" />
            <div class="template-vars">
              可用变量: {订单号}, {寄件人}, {收件人}, {创建时间}
            </div>
          </el-form-item>
          
          <el-form-item label="状态变更通知模板">
            <el-input v-model="combinedSettings.statusChangeTemplate" type="textarea" :rows="3" />
            <div class="template-vars">
              可用变量: {订单号}, {状态}, {更新时间}, {操作地点}
            </div>
          </el-form-item>
          
          <el-form-item label="签收通知模板">
            <el-input v-model="combinedSettings.deliveredTemplate" type="textarea" :rows="3" />
            <div class="template-vars">
              可用变量: {订单号}, {签收时间}, {签收人}
            </div>
          </el-form-item>
        </el-form>
      </div>
      
      <div class="settings-actions">
        <el-button 
          type="primary" 
          :loading="loading" 
          @click="saveSettings"
        >
          {{ loading ? '保存中...' : '保存设置' }}
        </el-button>
        <el-button 
          @click="resetSettings"
          :disabled="loading"
        >
          重置
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import { 
  getEmailSettings, 
  updateEmailSettings, 
  getNotificationSettings, 
  updateNotificationSettings,
  testEmailConnection,
  type EmailSettings,
  type NotificationSettings
} from '@/api/settings'

// 加载状态
const loading = ref(false)
const testingConnection = ref(false)

// 表单引用
const formRef = ref()

// SMTP服务商选择
const selectedSmtpProvider = ref('')

// 常用SMTP配置
const smtpConfigs = {
  '163': { server: 'smtp.163.com', port: 465, ssl: true },
  'qq': { server: 'smtp.qq.com', port: 587, ssl: true },
  'gmail': { server: 'smtp.gmail.com', port: 587, ssl: true },
  'enterprise': { server: '', port: 25, ssl: false }
}

// 选择SMTP服务商
const selectSmtpProvider = (provider: string) => {
  if (provider && smtpConfigs[provider as keyof typeof smtpConfigs]) {
    const config = smtpConfigs[provider as keyof typeof smtpConfigs]
    combinedSettings.smtpServer = config.server
    combinedSettings.smtpPort = config.port
    combinedSettings.useSSL = config.ssl
  }
  selectedSmtpProvider.value = ''
}

// 表单验证规则
const formRules = {
  smtpServer: [
    { required: true, message: '请输入SMTP服务器地址', trigger: 'blur' }
  ],
  smtpPort: [
    { required: true, message: '请输入SMTP端口', trigger: 'blur' },
    { type: 'number', min: 1, max: 65535, message: '端口范围为1-65535', trigger: 'blur' }
  ],
  senderEmail: [
    { required: true, message: '请输入发件人邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  emailPassword: [
    { required: true, message: '请输入邮箱密码或授权码', trigger: 'blur' }
  ]
}

// 邮件设置数据
const emailSettings = reactive<EmailSettings>({
  smtpServer: 'smtp.163.com',
  smtpPort: 465,
  senderEmail: 'system@example.com',
  emailPassword: '',
  useSsl: true
})

// 通知设置数据
const notificationSettings = reactive<NotificationSettings>({
  notifyOnCreate: true,
  notifyOnStatusChange: true,
  notifyOnDelivered: true,
  createTemplate: '尊敬的客户，您的快递订单 {订单号} 已创建成功，寄件人：{寄件人}，收件人：{收件人}，感谢您的使用。',
  statusChangeTemplate: '尊敬的客户，您的快递订单 {订单号} 状态已更新为 {状态}，更新时间：{更新时间}，当前位置：{操作地点}。',
  deliveredTemplate: '尊敬的客户，您的快递订单 {订单号} 已于 {签收时间} 签收，签收人：{签收人}，感谢您的使用。'
})

// 原始设置（用于重置）
let originalEmailSettings: EmailSettings = {} as EmailSettings
let originalNotificationSettings: NotificationSettings = {} as NotificationSettings

// 合并的设置对象（用于显示）
const combinedSettings = reactive({
  // 邮件设置
  enableEmail: true,
  smtpServer: emailSettings.smtpServer,
  smtpPort: emailSettings.smtpPort,
  senderEmail: emailSettings.senderEmail,
  emailPassword: emailSettings.emailPassword,
  useSSL: emailSettings.useSsl,
  
  // 通知设置
  notifyOnCreate: notificationSettings.notifyOnCreate,
  notifyOnStatusChange: notificationSettings.notifyOnStatusChange,
  notifyOnDelivered: notificationSettings.notifyOnDelivered,
  createTemplate: notificationSettings.createTemplate,
  statusChangeTemplate: notificationSettings.statusChangeTemplate,
  deliveredTemplate: notificationSettings.deliveredTemplate
})

// 加载设置数据
const loadSettings = async () => {
  loading.value = true
  try {
    // 并行获取邮件设置和通知设置
    const [emailRes, notificationRes] = await Promise.all([
      getEmailSettings(),
      getNotificationSettings()
    ])

    // 处理邮件设置
    if (emailRes.code === 200 && emailRes.data.success && emailRes.data.data) {
      Object.assign(emailSettings, emailRes.data.data)
      originalEmailSettings = JSON.parse(JSON.stringify(emailRes.data.data))
    }

    // 处理通知设置
    if (notificationRes.code === 200 && notificationRes.data.success && notificationRes.data.data) {
      Object.assign(notificationSettings, notificationRes.data.data)
      originalNotificationSettings = JSON.parse(JSON.stringify(notificationRes.data.data))
    }

    // 更新合并的设置对象
    updateCombinedSettings()
    
  } catch (error: any) {
    ElMessage.error('加载设置失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 更新合并的设置对象
const updateCombinedSettings = () => {
  combinedSettings.smtpServer = emailSettings.smtpServer
  combinedSettings.smtpPort = emailSettings.smtpPort
  combinedSettings.senderEmail = emailSettings.senderEmail
  combinedSettings.emailPassword = emailSettings.emailPassword
  combinedSettings.useSSL = emailSettings.useSsl
  
  combinedSettings.notifyOnCreate = notificationSettings.notifyOnCreate
  combinedSettings.notifyOnStatusChange = notificationSettings.notifyOnStatusChange
  combinedSettings.notifyOnDelivered = notificationSettings.notifyOnDelivered
  combinedSettings.createTemplate = notificationSettings.createTemplate
  combinedSettings.statusChangeTemplate = notificationSettings.statusChangeTemplate
  combinedSettings.deliveredTemplate = notificationSettings.deliveredTemplate
}

// 从合并的设置对象更新原始设置
const updateOriginalSettings = () => {
  emailSettings.smtpServer = combinedSettings.smtpServer
  emailSettings.smtpPort = combinedSettings.smtpPort
  emailSettings.senderEmail = combinedSettings.senderEmail
  emailSettings.emailPassword = combinedSettings.emailPassword
  emailSettings.useSsl = combinedSettings.useSSL
  
  notificationSettings.notifyOnCreate = combinedSettings.notifyOnCreate
  notificationSettings.notifyOnStatusChange = combinedSettings.notifyOnStatusChange
  notificationSettings.notifyOnDelivered = combinedSettings.notifyOnDelivered
  notificationSettings.createTemplate = combinedSettings.createTemplate
  notificationSettings.statusChangeTemplate = combinedSettings.statusChangeTemplate
  notificationSettings.deliveredTemplate = combinedSettings.deliveredTemplate
}

// 自动保存邮件设置
const autoSaveEmailSettings = async () => {
  try {
    updateOriginalSettings()
    await updateEmailSettings({
      smtpServer: emailSettings.smtpServer,
      smtpPort: emailSettings.smtpPort,
      senderEmail: emailSettings.senderEmail,
      emailPassword: emailSettings.emailPassword,
      useSsl: emailSettings.useSsl
    })
    // 更新原始设置
    originalEmailSettings = JSON.parse(JSON.stringify(emailSettings))
  } catch (error) {
    // 静默处理错误，不显示提示
    console.error('自动保存邮件设置失败:', error)
  }
}

// 自动保存通知设置
const autoSaveNotificationSettings = async () => {
  try {
    updateOriginalSettings()
    await updateNotificationSettings({
      notifyOnCreate: notificationSettings.notifyOnCreate,
      notifyOnStatusChange: notificationSettings.notifyOnStatusChange,
      notifyOnDelivered: notificationSettings.notifyOnDelivered,
      createTemplate: notificationSettings.createTemplate,
      statusChangeTemplate: notificationSettings.statusChangeTemplate,
      deliveredTemplate: notificationSettings.deliveredTemplate
    })
    // 更新原始设置
    originalNotificationSettings = JSON.parse(JSON.stringify(notificationSettings))
  } catch (error) {
    // 静默处理错误，不显示提示
    console.error('自动保存通知设置失败:', error)
  }
}

// 测试邮件连接
const testConnection = async () => {
  // 验证必填字段
  if (!combinedSettings.smtpServer) {
    ElMessage.warning('请先填写SMTP服务器地址')
    return
  }
  if (!combinedSettings.senderEmail) {
    ElMessage.warning('请先填写发件人邮箱')
    return
  }
  if (!combinedSettings.emailPassword) {
    ElMessage.warning('请先填写邮箱密码或授权码')
    return
  }

  testingConnection.value = true
  try {
    // 使用当前表单数据进行测试
    const testData: EmailSettings = {
      smtpServer: combinedSettings.smtpServer,
      smtpPort: combinedSettings.smtpPort,
      senderEmail: combinedSettings.senderEmail,
      emailPassword: combinedSettings.emailPassword,
      useSsl: combinedSettings.useSSL
    }
    
    const response = await testEmailConnection(testData)
    
    if (response.code === 200 && response.data.success) {
      ElMessage.success('邮件连接测试成功！')
    } else {
      ElMessage.error('邮件连接测试失败: ' + (response.data.message || '未知错误'))
    }
  } catch (error: any) {
    console.error('邮件连接测试错误:', error)
    ElMessage.error('邮件连接测试失败: ' + (error.message || error.msg || '网络错误'))
  } finally {
    testingConnection.value = false
  }
}

// 保存设置
const saveSettings = async () => {
  // 如果邮件通知开启，验证邮件设置
  if (combinedSettings.enableEmail) {
    try {
      await formRef.value?.validate()
    } catch (error) {
      ElMessage.warning('请完善邮件设置信息')
      return
    }
  }

  loading.value = true
  try {
    // 更新原始设置对象
    updateOriginalSettings()
    
    // 并行保存邮件设置和通知设置
    const [emailRes, notificationRes] = await Promise.all([
      updateEmailSettings({
        smtpServer: emailSettings.smtpServer,
        smtpPort: emailSettings.smtpPort,
        senderEmail: emailSettings.senderEmail,
        emailPassword: emailSettings.emailPassword,
        useSsl: emailSettings.useSsl
      }),
      updateNotificationSettings({
        notifyOnCreate: notificationSettings.notifyOnCreate,
        notifyOnStatusChange: notificationSettings.notifyOnStatusChange,
        notifyOnDelivered: notificationSettings.notifyOnDelivered,
        createTemplate: notificationSettings.createTemplate,
        statusChangeTemplate: notificationSettings.statusChangeTemplate,
        deliveredTemplate: notificationSettings.deliveredTemplate
      })
    ])

    // 检查保存结果
    const emailSuccess = emailRes.code === 200 && emailRes.data.success
    const notificationSuccess = notificationRes.code === 200 && notificationRes.data.success

    if (emailSuccess && notificationSuccess) {
      ElMessage.success('设置保存成功！')
      // 更新原始设置
      originalEmailSettings = JSON.parse(JSON.stringify(emailSettings))
      originalNotificationSettings = JSON.parse(JSON.stringify(notificationSettings))
    } else {
      const errors = []
      if (!emailSuccess) errors.push('邮件设置保存失败')
      if (!notificationSuccess) errors.push('通知设置保存失败')
      ElMessage.error(errors.join(', '))
    }
    
  } catch (error: any) {
    console.error('保存设置错误:', error)
    ElMessage.error('保存设置失败: ' + (error.message || error.msg || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 重置设置
const resetSettings = () => {
  // 重置为原始设置
  Object.assign(emailSettings, originalEmailSettings)
  Object.assign(notificationSettings, originalNotificationSettings)
  updateCombinedSettings()
  ElMessage.info('已重置为上次保存的设置')
}

onMounted(() => {
  loadSettings()
})
</script>

<style scoped>
.settings-container {
  padding: 20px;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.tab-content {
  padding: 0 20px;
}

.tab-content h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 20px 0;
  color: #409EFF;
}

.settings-form {
  max-width: 800px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-left: 10px;
}

.template-vars {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.settings-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

:deep(.el-input-number) {
  width: 180px;
}
</style> 